# a=map(int,input().split())
# lst = list(a)
# print(lst)
# nb = list(a)
# print(nb)
# b = "berioHHJJ"
# b.lower()
from datetime import datetime

# import requests,pymysql
# from time import sleep
#
# #建立数据库连接：
# connection = pymysql.connect(
#     host='192.168.248.130',
#     user='root',
#     password='',
#     database='web',
#     charset='utf8mb4',
#     port=3306,
#     cursorclass=pymysql.cursors.DictCursor
# )
# lst =['http://192.168.100.157/feng.html',
# 'http://192.168.100.157/zhang.html',
# 'http://192.168.100.157/',
# 'http://192.168.100.157/sc.html',
# 'http://192.168.100.157/li.html',
# 'http://www.qq.com',
# 'https://www.jd.com/feng.html']
#
# # response = requests.get('http://192.168.100.157/feng.html')
# # response = requests.get('https://www.jd.com/feng.html')
# # # timeout = 5
# # #获取状态码
# # status_code = response.status_code
# # print(status_code)
# # # 获取最终请求URL（考虑重定向）
# # final_url = response.url
# # print(f"最终URL: {final_url}")
# # headers = response.headers
# # print(headers)
# # # 获取请求头（查看发送的请求头）
# # request_headers = response.request.headers
# # print(f"请求头: {request_headers}")
#
# for url in lst:
#     response = requests.get(url)
#     status_code = response.status_code
#     with connection.cursor() as cursor:
#         sql = """
#         insert into access_url (url,status_code) values(%s,%s)
#               """
#         cursor.execute(sql,(url,status_code))
#     connection.commit()
#     sleep(1)
# connection.close()


import requests
import pymysql
from time import sleep
from requests.exceptions import RequestException
import datetime  # 新增：导入datetime模块

# 建立数据库连接
conn = pymysql.connect(
    host='192.168.248.135',
    user='root',
    password='@0713NBwq',  # 实际密码，若为空需修改
    database='web',
    charset='utf8mb4',
    port=3306,
    cursorclass=pymysql.cursors.DictCursor
)

cursor = conn.cursor()

#增加
try:
    sql = "insert into access_url (url,status_code,time)values(%s,%s,now())"
    data = ("ceshi","0")
    cursor.execute(sql, data)
    conn.commit()
    print("执行成功")
except Exception as e:
    conn.rollback()
    print("执行失败")

#删除
try:
    sql = "delete from access_url where url = %s"
    url = "ceshi"
    cursor.execute(sql,url)
    conn.commit()
    print("执行成功")
except Exception as e:
    conn.rollback()
    print("执行失败")

#修改
try:
    sql = "update access_url set status_code = %s where url = %s"
    status_code = "10086"
    url = "http://192.168.100.157/li.html"
    cursor.execute(sql,(status_code,url))
    conn.commit()
    print(f"更新成功,url为{url}的对象对应的状态码已改为{status_code}")
except Exception as e:
    conn.rollback()
    print("更新失败")

#查询
try:
    sql = "select * from access_url"
    cursor.execute(sql)

    #获取所有的结果
    results = cursor.fetchall()
    print(f"查询到{len(results)}条记录")
    for row in results:
        print(row)
except Exception as e:
    print("查询失败")



# URL列表扩展：新增请求方法（GET/POST），修正第一个URL的端口
# lst = [
#     ("http://192.168.248.135:80", "GET"),  # 补充端口（假设Nginx监听80）
#     ("http://192.168.100.157/feng.html", "GET"),
#     ("http://192.168.100.157/zhang.html", "POST"),  # 示例POST
#     ("http://192.168.100.157/", "GET"),
#     ("http://192.168.100.157/sc.html", "GET"),
#     ("http://192.168.100.157/li.html", "POST"),  # 示例POST
#     ("http://www.qq.com", "GET"),
#     ("https://www.jd.com/feng.html", "GET")
# ]
#
# # 自定义请求头部（模拟浏览器）
# headers = {
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
# }
#
# # 遍历URL并处理GET/POST请求
# for url, method in lst:  # 遍历（URL, 方法）元组
#     try:
#         print(f"正在访问: {url}，方法: {method}")
#
#         # 根据方法发送请求
#         if method == "GET":
#             response = requests.get(url, headers=headers, timeout=5)
#         elif method == "POST":
#             response = requests.post(url, headers=headers, data={}, timeout=5)  # POST可带data参数
#         else:
#             print(f"不支持的方法: {method}，跳过该URL")
#             sleep(1)
#             print("-" * 50)
#             continue
#
#         status_code = response.status_code
#
#         # 插入数据库（参数化查询防SQL注入）
#         with connection.cursor() as cursor:
#             now_time = datetime.datetime.now()  # 正确调用：datetime.datetime.now()
#             sql = """
#                   INSERT INTO access_url (url, status_code, time)
#                   VALUES (%s, %s, %s) \
#                   """
#             cursor.execute(sql, (url, status_code, now_time))
#         connection.commit()
#         print(f"已保存: {url} -> {status_code}")
#
#     except RequestException as req_err:
#         print(f"请求 {url} 时出错: {req_err}")
#         # 错误信息插入数据库（状态码设为0）
#         try:
#             with connection.cursor() as cursor:
#                 now_time = datetime.datetime.now()
#                 sql = """
#                       INSERT INTO access_url (url, status_code, time)
#                       VALUES (%s, %s, %s) \
#                       """
#                 cursor.execute(sql, (url, 0, now_time))
#             connection.commit()
#             print(f"已保存错误信息: {url} -> 0")
#         except pymysql.MySQLError as db_err:
#             print(f"数据库插入失败: {db_err}")
#
#     sleep(1)
#     print("-" * 50)

# 关闭数据库连接和游标
cursor.close()
conn.close()

# print("所有URL处理完成！")
